const mongoose = require('mongoose');
const News=require('../model/news.model');


//增
exports.create=function(req,res,next){
    const news=new News(req.body);//实例化对象,req,body表示post的数据提交,并且参数从body中获取
    news.save().then(data=>{//数据保存,在保存后将数据用json格式输出
        res.json(data);
    })
}
//删
exports.remove=function(req,res,next){
    var id=req.params.id;
    News.findByIdAndRemove(id,function(err,data){
        res.json({message:'删除成功'});
    })
}

//改
//参数三种传递方式:req.body,req.query,req.params
exports.update=function(req,res,next){
    const id=req.params.id;//查找一个id
    News.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);
    })
}

//查

exports.list=function(req,res,next){
    var page=req.body.page?req.body.page:1;
    var limit=req.body.limit?req.body.limit:5;
    var queryCondition={};

    if(req.body.title && req.body.title.trim().length>0){
        title=req.body.title;
        queryCondition={
            title:new RegExp(title,'i')
        }
    }


    if(req.body.cateId && req.body.cateId.trim().length>0){
        cateId=req.body.cateId;
        queryCondition=Object.assign(queryCondition,{//assign对象合并
            cateId:cateId
        });
    }
    News.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
        result.rows=result.docs;
        delete result.docs;
        res.json(result);
      });
}